/*	kd:
	
	Item buttons can now have particle effects attached. This generalises the
	"new item glow" from previous versions. They won't disappear after being
	viewed once and stick to the button's centre.
	
	You can add a particle effect to an item when you define it for a shop
	(in the AddForSale function). Check out here be shops.txt for an example.
	All the secret items have little twinkling stars.
	
	*/

struct Gc_Shop_ItemFx {
	private Gc_ScreenParticles		particle_fx;
	private Array <int>				item_index;
	
	void OnBuild (Gc_Rng rng) {
		particle_fx.OnBuild(rng);
	}
	
	// kd: Each item can have a generator class assigned, so on load, we wanna
	// instantiate them.
	void OnInventoryLoad (Gc_Shop_Inv inv) {
		ClearAll();
		
		for(let i = 0; i < inv.ItemCount(); i++) {
			let gen = inv.ParticleGen(i);
			
			if(gen) {
				let gen_inst = Gc_ScreenParticleGen(new(gen));
			
				if(gen_inst) {
					particle_fx.Add(gen_inst);
					
					// kd: Store the index to the item. Not all of them have a
					// particle generator, so we need this to know what to stick
					// this one to.
					item_index.push(i);
				}
			} // THUD
		} // THUD
	} // THUD
	// THUD ouch what a staircase
	
	// kd: Makes all the generators begin their particle emission thingy.
	void Trigger () {
		for(let i = item_index.size(); 0 <= --i; ) {
			let gen_inst = particle_fx.GeneratorAt(i);
			
			if(gen_inst) {
				gen_inst.Trigger();
			}
		}
	}
	
	void ClearAll () {
		particle_fx.DestroyGenerators();
		item_index.clear();
	}
	
	void StickToLayout (Gc_Shop_InvLayout layout, vector2 resolution) {
		
		// kd: We have to rescale from the buttons that live in a totally
		// different resolution.
		let scale = (
			resolution.x / layout.rscreen.width,
			resolution.y / layout.rscreen.height);
		
		// kd: Make sure all the stuff sticks.
		for(let i = particle_fx.GeneratorCount(); 0 <= --i;) {
			let gen_inst = particle_fx.GeneratorAt(i);
			
			if(gen_inst) {
				// kd: This one lives in a different resolution, of course.
				let origin = layout.NormalOrigin(item_index [i]);
				
				origin.x *= scale.x;
				origin.y *= scale.y;
				
				gen_inst.SetOrigin(origin);
			}
		}
	}
	
	void NextState () {
		// kd: We need a bit of a custom removing done generators here, cuz if
		// you put something like an explosion on an item, it'll get striked off
		// the list and then your particle effects will go to other items.
		
		for(let i = particle_fx.GeneratorCount(); 0 <= --i;) {
			let gen_inst = particle_fx.GeneratorAt(i);
			
			if(!gen_inst || gen_inst.IsDone()) {
				particle_fx.Remove(i);
				item_index.delete(i);
			}
		}
		
		particle_fx.NextState();
	}
	
	ui void Draw (vector2 resolution, double t = 1) const {
		particle_fx.Draw(resolution, t);
	}
}
